//
//  TCFirstViewController.m
//  TrustCloud
//
//  Created by NetApp on 16/7/13.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "TCFirstViewController.h"
#import <Masonry.h>
#import "TCBanner+Config.h"
#import <DDLog.h>
#import "MBProgressHUD+TC.h"
#import "TCConfiguration.h"
#import "TCHomeCollectionViewCell.h"
#import "UIImage+TC.h"
#import "KxMenu.h"
#import "UIColor+ICT.h"

#ifdef DEBUG
static const int ddLogLevel = LOG_LEVEL_DEBUG;
#else
static const int ddLogLevel = LOG_LEVEL_OFF;
#endif

#define kBannerFunctuionVersion @"0.0.1"

extern CGFloat      const kImageCompressionRatio;

static CGFloat      const kBannerHeight = 165.0;
static NSInteger    const kButtonTagPrefix = 300;     //监测页底部UICollectionViewCell按钮Tag前缀

static NSString *   const kCellIdentify = @"COLLECTION_CELL";

@interface TCFirstViewController ()
<UICollectionViewDelegate,
UICollectionViewDataSource,
UICollectionViewDelegateFlowLayout
>

typedef NS_ENUM(NSUInteger, YWKMonitorCollectionCellRow) {
    
    YWKMonitorCollectionCellRowMeasure = 0,
    YWKMonitorCollectionCellRowDiseaseManage,
    YWKMonitorCollectionCellRowHistoryData,
    YWKMonitorCollectionCellRowReport
};

@property (nonatomic, strong)   UICollectionView            *featureCollectionView;

@property (nonatomic, strong)   TCBanner                  *banner;
@property (nonatomic, copy)     NSArray                     *bannerInfos;

@property (nonatomic, copy)     NSDictionary                    *reportInfo;

@property (nonatomic, copy)     NSArray                     *cellImgNames;              //UICollectionViewCell的图片
@property (nonatomic, copy)     NSArray                     *cellTexts;                 //UICollectionViewCell文本

@property (nonatomic)           CGFloat                     cellWidth;
@property (nonatomic)           CGFloat                     cellHeight;

@property (nonatomic, strong)   MBProgressHUD               *hud;

@end

@implementation TCFirstViewController

#pragma mark - life cycle

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        
        self.edgesForExtendedLayout = UIRectEdgeNone;
        self.navigationController.navigationBar.translucent = NO;
        _cellWidth = 0.5 * UI_SCREEN_WIDTH;
        _cellHeight = 0.5 * (UI_SCREEN_HEIGHT - kBannerHeight - 113);
//        [[NSNotificationCenter defaultCenter] addObserver:self
//                                                 selector:@selector(logout:)
//                                                     name:YWKLoginOutNotification
//                                                   object:nil];
    }
    return self;
}

- (void)loadView
{
    [super loadView];
    
    self.navigationItem.title = NSLocalizedString(@"财富云", nil);
    
    UIBarButtonItem *addDeviceBtn = [[UIBarButtonItem alloc] initWithCustomView:[self configAddDeviceButton]];
    self.navigationItem.rightBarButtonItem = addDeviceBtn;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //hud添加到self.View，不会遮挡self.view上面的控件
    [self.view addSubview:self.hud];
    [self configCollectionView];
}

- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated{
    
    [super viewDidAppear:animated];
    
    [self.hud show:YES];
}

- (void)viewDidDisappear:(BOOL)animated{
    
  
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UICollectionViewDataSource

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return self.cellImgNames.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    TCHomeCollectionViewCell *cell = [self.featureCollectionView
                                          dequeueReusableCellWithReuseIdentifier:kCellIdentify
                                          forIndexPath:indexPath];
    [cell sizeToFit];
    
    UIImage *image = [UIImage imageNamed:self.cellImgNames[indexPath.row]];
    if (UI_SCREEN_HEIGHT < 568) {
        image = [image imageCompressByRatio:kImageCompressionRatio];
    }
    cell.featureItemBtn.imgSize = image.size;
    
    [cell.featureItemBtn setImage:image forState:UIControlStateNormal];
    
    cell.featureItemBtn.firstLineString = self.cellTexts[indexPath.row];
    [cell.featureItemBtn setAdjustTitleforState:UIControlStateNormal];
    
    cell.featureItemBtn.frame = [cell.featureItemBtn adjustFrame];
    cell.featureItemBtn.center = cell.contentView.center;
    
    cell.featureItemBtn.tag = kButtonTagPrefix + indexPath.row;
    [cell.featureItemBtn addTarget:self action:@selector(collectionFeatureButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    
    return cell;
}

#pragma mark - UICollectionViewDelegate

- (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    return NO;
}

#pragma mark - UICollectionViewDelegateFlowLayout

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake(self.cellWidth, self.cellHeight);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 0;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 0;
}

#pragma mark - event response

- (void)loginSuccess:(NSNotification *)notification{
    
}

- (void)logout:(NSNotification *)notification{
    
    
}

/**
 *  添加设备
 *
 *  @param sender "+"
 */
- (void)addDevice:(UIButton *)sender
{
    [KxMenu setTintColor:[UIColor whiteColor]];
    NSArray *menuItems =
    @[
      
      [KxMenuItem menuItem:@"设备管理"
                     image:[UIImage imageNamed:@"navDown_add"]
                    target:self
                    action:@selector(deviceManage:)],
      
      [KxMenuItem menuItem:@"免费随访（测试）"
                     image:[UIImage imageNamed:@"navDown_scan"]
                    target:self
                    action:@selector(pushMenuItemScan:)]
      ];
    
    
    KxMenuItem *first = menuItems[0];
    first.foreColor = [UIColor blackColor];
    first.alignment = NSTextAlignmentCenter;
    KxMenuItem *second = menuItems[1];
    second.foreColor = kYWKTextMakoColor;
    second.alignment = NSTextAlignmentCenter;
    
    first.alignment = NSTextAlignmentCenter;
    [KxMenu showMenuInView:self.navigationController.view
                  fromRect:CGRectMake(sender.frame.origin.x,
                                      sender.frame.origin.y + 20,
                                      sender.frame.size.width,
                                      sender.frame.size.height)
                 menuItems:menuItems];
}

/**
 *  监测页底部CollectionViewCell中Button被点击
 *
 *  @param sender 被点击的Button
 */
- (void)collectionFeatureButtonClicked:(UIButton *)sender
{
    
    switch (sender.tag - kButtonTagPrefix)
    {
        case YWKMonitorCollectionCellRowMeasure:
        {
//            YWKMeasureViewController *mesureVC = [[YWKMeasureViewController alloc] init];
//            mesureVC.hidesBottomBarWhenPushed = YES;
//            [self.navigationController pushViewController:mesureVC animated:YES];
        }
            break;
            
        case YWKMonitorCollectionCellRowDiseaseManage:
        {
            
//            YWKMonitorPlanListVC *plan = [[YWKMonitorPlanListVC alloc] init];
//            plan.hidesBottomBarWhenPushed = YES;
//            [self.navigationController pushViewController:plan animated:YES];
        }
            break;
            
        case YWKMonitorCollectionCellRowHistoryData:
        {
//            if (user.userName) {
//                
//                YWKHistoryDataViewController *historyVC = [[YWKHistoryDataViewController alloc] initWithUserName:@""];
//                historyVC.hidesBottomBarWhenPushed = YES;
//                [self.navigationController pushViewController:historyVC animated:YES];
//            }else{
//                
//                [[NSNotificationCenter defaultCenter] postNotificationName:YWKShowLoginNotificateion
//                                                                    object:nil];
//            }
            
        }
            break;
            
        case YWKMonitorCollectionCellRowReport:
//        {
//            //            YWKReportListViewController *reportListVC = [[YWKReportListViewController alloc] init];
//            self.loginHander = [YWKLoginHander loginHandler];
//            self.currentUser = self.loginHander.account;
//            if (!self.currentUser.userName) {
//                
//                [[NSNotificationCenter defaultCenter] postNotificationName:YWKShowLoginNotificateion
//                                                                    object:nil];
//            }
//            else
//            {
//                NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
//                NSDictionary * userCookie = [defaults objectForKey:@"login"];
//                if (!userCookie) {
//                    
//                    userCookie = [NSDictionary dictionaryWithObjects:@[self.currentUser.userName, [NSDate date]]
//                                                             forKeys:@[@"user", @"date"]];
//                    [defaults setObject:userCookie forKey:@"login"];
//                    
//                    YWKSleepTimeViewController * sleepTimeVC = [[YWKSleepTimeViewController alloc]init];
//                    sleepTimeVC.hidesBottomBarWhenPushed = YES;
//                    [self.navigationController pushViewController:sleepTimeVC animated:YES];
//                }
//                else
//                {
//                    NSDateFormatter * ymd = [NSDateFormatter YMDPointDateFormatter];
//                    NSDate * now = [NSDate date];
//                    NSString * nowString = [ymd stringFromDate:now];
//                    NSString * lastString = [ymd stringFromDate:userCookie[@"date"]];
//                    if (![userCookie[@"user"] isEqualToString:self.currentUser.userName] ||
//                        ![nowString isEqualToString:lastString]) {
//                        
//                        YWKSleepTimeViewController * sleepTimeVC = [[YWKSleepTimeViewController alloc]init];
//                        sleepTimeVC.hidesBottomBarWhenPushed = YES;
//                        [self.navigationController pushViewController:sleepTimeVC animated:YES];
//                    }
//                    else
//                    {
//                        YWKReportListViewController * reportListVC = [[YWKReportListViewController alloc]init];
//                        reportListVC.hidesBottomBarWhenPushed = YES;
//                        [self.navigationController pushViewController:reportListVC animated:YES];
//                    }
//                }
//            }
//        }
            break;
        default:
            NSLog(@"no such a collection cell");
            break;
    }
}

/**
 *  设备管理
 *
 *  @param sender UIButton
 */
- (void)deviceManage:(UIButton *)sender{
    
//    YWKDeviceManageViewController *deviceMgrVC = [[YWKDeviceManageViewController alloc] init];
//    deviceMgrVC.hidesBottomBarWhenPushed = YES;
//    [self.navigationController pushViewController:deviceMgrVC animated:YES];
}

#warning --Custom--Wangd--To delete

- (void)pushMenuItemScan:(UIButton *)sender{
    
//    [self.freeFollowUpPopMode  popFreeFollowUpTipsWithDeviceSerialNum:@"1215100945"
//                                                           cancelType:YWKFreeFollowUpCancelTypeNotRemindAgain];
}

#pragma mark - private methods

/**
 *  添加设备按钮
 *
 *  @return UIButton
 */
- (UIButton *)configAddDeviceButton{
    UIButton *addDeviceBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    
    UIImage *image = [UIImage imageNamed:@"nav_add"];
    addDeviceBtn.frame = CGRectMake(0, 11, image.size.width, image.size.height);
    
    [addDeviceBtn setBackgroundImage:image forState:UIControlStateNormal];
    [addDeviceBtn addTarget:self action:@selector(addDevice:) forControlEvents:UIControlEventTouchUpInside];
    
    return addDeviceBtn;
}

/**
 *  配置并添加Banner
 */
- (void)configBanner {
    
    [self.banner configBannerAtView:self.view withArray:self.bannerInfos isAutoScroll:NO];
}

/**
 *  配置并添加UICollectionView
 */
- (void)configCollectionView
{
    [self.view addSubview:self.featureCollectionView];
    [self.featureCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.size.mas_equalTo(CGSizeMake(UI_SCREEN_WIDTH, 2 * self.cellHeight));
        make.top.equalTo(self.view).with.offset(kBannerHeight);
        make.left.equalTo(self.view);
    }];
}

#pragma mark - getters

- (UICollectionView *)featureCollectionView{
    
    if (!_featureCollectionView){
        
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.scrollDirection = UICollectionViewScrollDirectionVertical;
        
        _featureCollectionView = [[UICollectionView alloc] initWithFrame:CGRectZero
                                                    collectionViewLayout:layout];
        _featureCollectionView.backgroundColor = [UIColor whiteColor];
        
        _featureCollectionView.dataSource = self;
        _featureCollectionView.delegate = self;
        
        _featureCollectionView.alwaysBounceVertical = YES;
        _featureCollectionView.contentSize = CGSizeMake(UI_SCREEN_WIDTH, self.cellTexts.count * self.cellHeight + 1);
        
        [_featureCollectionView registerClass:[TCHomeCollectionViewCell class] forCellWithReuseIdentifier:kCellIdentify];
        
        /**CollectionView中间的十字线********************************************************************/
        
        CGFloat lineHorizontalX;
        CGFloat lineHorizontalW;
        CGFloat lineHorizontalY = self.cellHeight - 0.5;
        CGFloat lineHorizontalH = 1;
        
        if (UI_SCREEN_HEIGHT >= 568) {
            
            lineHorizontalX = 16;
            lineHorizontalW = (UI_SCREEN_WIDTH - 32);
            
        }else{
            lineHorizontalX = 16 * kImageCompressionRatio;
            lineHorizontalW = (UI_SCREEN_WIDTH - 32 * kImageCompressionRatio);
        }
        
        UIView *lineHorizontal = [[UIView alloc] initWithFrame:CGRectMake(lineHorizontalX,
                                                                          lineHorizontalY,
                                                                          lineHorizontalW,
                                                                          lineHorizontalH)];
        lineHorizontal.backgroundColor = [UIColor colorWithHex:0xDCDEE0];
        [self.featureCollectionView addSubview:lineHorizontal];
        
        CGFloat lineVerticalX = self.cellWidth - 0.5;
        CGFloat lineVerticalW = 1;
        CGFloat lineVerticalY;
        CGFloat lineVerticalH;
        
        if (UI_SCREEN_HEIGHT >= 568) {
            
            lineVerticalY = 16;
            lineVerticalH = 2 * (self.cellHeight - 16);
            
        }else{
            lineVerticalY = 8;
            lineVerticalH = 2 * (self.cellHeight - 8);
        }
        
        UIView *lineVertical = [[UIView alloc] initWithFrame:CGRectMake(lineVerticalX,
                                                                        lineVerticalY,
                                                                        lineVerticalW,
                                                                        lineVerticalH)];
        
        lineVertical.backgroundColor = [UIColor colorWithHex:0xDCDEE0];
        [self.featureCollectionView addSubview:lineVertical];
        
        /***********************************************************************************************/
    }
    
    return _featureCollectionView;
}

- (TCBanner *)banner{
    
    if (_banner == nil) {
        
        _banner = [[TCBanner alloc] initWithMonitorResultAndFrame:CGRectMake(0,
                                                                              0,
                                                                              UI_SCREEN_WIDTH,
                                                                              kBannerHeight)];
    }
    
    return _banner;
}

- (NSArray *)bannerInfos{
    
    if (_bannerInfos == nil) {
        
        _bannerInfos = [NSArray array];
    }
    
    return _bannerInfos;
}

- (NSArray *)cellImgNames{
    
    if (!_cellImgNames) {
        
        _cellImgNames = @[@"collecCell_monitor_measure",
                          @"collecCell_monitor_program",
                          @"collecCell_monitor_historyData",
                          @"collecCell_monitor_report"];
    }
    
    return _cellImgNames;
}

- (NSArray *)cellTexts{
    
    if (!_cellTexts) {
        
        _cellTexts = @[@"立即测量", @"慢病管理方案", @"历史数据", @"专业报告"];
    }
    
    return _cellTexts;
}

- (MBProgressHUD *)hud{
    
    if (!_hud) {
        
        _hud = [MBProgressHUD YWKProgressLoadingInView:self.banner];
        _hud.frame = CGRectMake(0, 0, self.banner.frame.size.width, self.banner.frame.size.height);
        _hud.frame = CGRectZero;
        _hud.backgroundColor = [UIColor colorWithWhite:1.f alpha:0.9];
        _hud.removeFromSuperViewOnHide = YES;
    }
    
    return _hud;
}

- (NSDictionary *)reportInfo{
    
    if (!_reportInfo) {
        
        _reportInfo = @{};
    }
    
    return _reportInfo;
}



@end
